package com.wisdom.client.cluster;

import com.wisdom.client.config.ClientRpcConfig;
import com.wisdom.core.annotation.WisdomLoadBalance;
import com.wisdom.core.enums.StatusEnum;
import com.wisdom.core.exception.RpcException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @description: <默认的根据配置获取负载均衡算法>
 * @author: Leo
 * @date: 2021-08-29 17:48
 */
@Component
public class DefaultStrategyProvider implements StrategyProvider, ApplicationContextAware {

    @Autowired
    private ClientRpcConfig config;

    private ClientLoadBalanceStrategy clientLoadBalanceStrategy;

    @Override
    public ClientLoadBalanceStrategy getLoadBalanceStrategy() {
        return clientLoadBalanceStrategy;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        String strategy = config.getStrategy();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(WisdomLoadBalance.class);
        for (Object bean : beansWithAnnotation.values()) {
            WisdomLoadBalance wisdomLoadBalance = bean.getClass().getAnnotation(WisdomLoadBalance.class);
            if (wisdomLoadBalance.strategy().getValue().equals(strategy)) {
                clientLoadBalanceStrategy = (ClientLoadBalanceStrategy) bean;
                break;
            }
        }
        if (clientLoadBalanceStrategy == null) {
            throw new RpcException(StatusEnum.NOT_FOUND_LOAD_BALANCE);
        }
    }
}
